/* eslint no-unused-vars:0 */
import React, { Component } from 'react';
import Axios from 'axios';
import {
    Modal,
    Button,
    Menu,
    Col,
    Row,
    Icon,
    Input,
    Select,
    Table,
    Pagination,
    Spin
} from 'antd';
import 'whatwg-fetch';
import WrappedAddSolutionForm from './AddForm';
import './index.less';
import { Link } from 'react-router-dom';
import PageComponent from './pageComponent.jsx';
const Search = Input.Search;
const Option = Select.Option;

//Modal代码
class ManageRisk extends Component {
    state = {
        ////////
        ModalText: 'Content of the modal',
        visible: false,
        TipVisible: false,
        TipMSG: '操作成功,请刷新页面 ',
        confirmLoading: false,
        riskTypes: [],
        referenceLevels: [],
        searchTypeInput: '',
        searchLevelInput: '',
        deleteSolutionInput: '',

        indexList: [], // 获取数据的存放数组
        totalNum: '', // 总记录数
        totalData: [],
        current: 1, //当前页码
        pageSize: 5, //每页显示的条数5条
        goValue: '',
        totalPage: '', //总页数
        columns: [
            {
                title: '标题',
                dataIndex: 'title',
                width: 250,
                className: 'blodFont'
            },
            {
                title: '类别',
                dataIndex: 'risk.riskType.type',
                className: 'blodFont',
                width: 120,
                render: (text, record) => (
                    <span
                        className={
                            record.referenceLevel.level == '重点参考'
                                ? 'tableColRed'
                                : record.referenceLevel.level == '一般参考'
                                ? 'tableColBlue'
                                : 'tableColGrey'
                        }>
                        {text}
                    </span>
                )
            },
            {
                title: '参考水平',
                dataIndex: 'referenceLevel.level',
                className: 'blodFont',
                width: 120,
                render: (text) => (
                    <span
                        className={
                            text == '重点参考'
                                ? 'tableColRed'
                                : text == '一般参考'
                                ? 'tableColBlue'
                                : 'tableColGrey'
                        }>
                        {text}
                    </span>
                )
            },
            {
                title: '详情',
                dataIndex: 'content',
                width: 120
            },
            {
                title: '方案ID',
                dataIndex: 'id',
                width: 150,
                render: (text) => <span>{text}</span>
            }
        ]
    };
    //点击翻页
    pageClick(pageNum) {
        var _this = this; //如果不定义就会出现作用域的问题this.setState不是一个函数
        if (pageNum != _this.state.current) {
            _this.state.current = pageNum;
        }

        _this.state.indexList = []; //清空之前的数据

        let temp = {
            type: _this.state.searchTypeInput,
            level: _this.state.searchLevelInput,
            pageSize: _this.state.pageSize,
            pageNum: _this.state.current - 1
        };

        console.log(_this.state.searchTypeInput);
        console.log(_this.state.searchLevelInput);
        console.log(temp);

        this.$get('/riskSolution/findAll', temp)
            .then((res) => {
                console.log(res);
                if (res) {
                    ///
                    _this.setState({ totalData: res.solutions.content });
                    _this.setState({ totalNum: res.solutions.totalElements });
                    //计算总页数= 总记录数 / 每页显示的条数
                    let totalPage = Math.ceil(
                        _this.state.totalNum / _this.state.pageSize
                    );
                    _this.setState({ totalPage: totalPage });

                    _this.state.indexList = []; //清空之前的数据
                    for (var i = 0; i < _this.state.pageSize; i++) {
                        if (_this.state.totalData[i]) {
                            _this.state.indexList.push(
                                _this.state.totalData[i]
                            );
                        }
                    }
                    _this.setState({ indexList: _this.state.indexList });
                }
            })
            .catch((e) => {
                console.log('error');
            });
    }

    //上一步
    goPrevClick() {
        var _this = this;
        let cur = this.state.current;
        if (cur > 1) {
            _this.pageClick(cur - 1);
        }
    }

    //下一步
    goNext() {
        var _this = this;
        let cur = _this.state.current;
        //alert(cur+"==="+_this.state.totalPage)
        if (cur < _this.state.totalPage) {
            _this.pageClick(cur + 1);
        }
    }

    // 跳转到指定页
    goSwitchChange(e) {
        var _this = this;
        _this.setState({ goValue: e.target.value });
        var value = e.target.value;
        // alert(value+"==="+_this.state.totalPage)
        if (!/^[1-9]\d*$/.test(value)) {
            alert('页码只能输入大于1的正整数');
        } else if (parseInt(value) > parseInt(_this.state.totalPage)) {
            alert('没有这么多页');
        } else {
            _this.pageClick(value);
        }
    }

    // ================================  //
    handleOk = (e) => {
        //点击对话框OK按钮触发的事件
        console.log();

        let demo = this.refs.getFormVlaue; //通过refs属性可以获得对话框内form对象
        demo.validateFields((err, values) => {
            if (!err) {
                console.log(values); //这里可以拿到数据
                let addParam = {
                    riskId: values.riskId,
                    content: values.content,
                    referenceLevel: values.referenceLevel.label,
                    url: values.url,
                    tipFlag: values.tipFlag
                };
                this.$post('/riskSolution/addSolution', addParam)
                    .then((res) => {
                        this.setState({});
                    })
                    .catch((e) => {
                        console.log(e);
                    });
                //
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoading: false,
                    visible: false,
                    deleteRiskVisible: true
                });
                // 上面的代码可以忽略
                //
            } else {
                this.setState({
                    ModalText: 'The modal will be closed after two seconds',
                    confirmLoading: false,
                    visible: false,
                    TipVisible: true
                });
            }
        });
    };

    handleCancel = () => {
        //点击取消按钮触发的事件
        console.log('Clicked cancel button');
        this.setState({
            visible: false,
            TipVisible: false
        });
    };

    findRiskTypes() {
        this.$get('/risk/findAllRiskTypes')
            .then((res) => {
                this.setState({
                    riskTypes: res.riskTypes
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }

    findLevelTypes() {
        this.$get('/riskSolution/findAllReferenceLevels')
            .then((res) => {
                this.setState({
                    referenceLevels: res.allReferenceLevels
                });
            })
            .catch((e) => {
                console.log(e);
            });
    }

    handleChangeLevel(e) {
        if (e) {
            this.setState({
                searchLevelInput: e.label
            });
        } else {
            this.setState({
                searchLevelInput: ''
            });
        }
    }

    handleChangeType(e) {
        if (e) {
            this.setState({
                searchTypeInput: e.label
            });
        } else {
            this.setState({
                searchTypeInput: ''
            });
        }
    }

    handleClickForSearch() {
        this.pageClick(this.state.current);
    }

    componentWillMount() {
        this.pageClick(1);
        this.findRiskTypes();
        this.findLevelTypes();
    }
    handleAddSolution(data) {
        this.setState({
            visible: true
        });
    }
    handleTipOk = () => {
        this.setState({
            TipVisible: false
        });
    };
    handleTipCancel = () => {
        this.setState({
            TipVisible: false
        });
    };
    onChangeDeleteSolutionInput(data) {
        if (data) {
            this.setState({
                deleteSolutionInput: data.target.value
            });
        } else {
            this.setState({
                deleteSolutionInput: ''
            });
        }
    }
    handleDeleteSolution() {
        if (this.state.deleteSolutionInput == '') {
            this.setState({
                TipMSG: 'ID错误,请输入正确的ID ',
                TipVisible: true
            });
            return;
        }
        let deleteSolutionId = {
            solutionId: this.state.deleteSolutionInput
        };

        this.$get('/riskSolution/deleteSolution', deleteSolutionId)
            .then((res) => {
                this.setState({
                    deleteSolutionInput: '',
                    TipMSG: '操作成功,请刷新页面 '
                });
            })
            .catch((e) => {
                console.log(e);
            });
        this.setState({
            TipVisible: true
        });
    }
    render() {
        const {
            deleteRiskVisible,
            TipVisible,
            visible,
            confirmLoading,
            ModalText
        } = this.state;
        return (
            <div className="myDiv">
                <div>
                    <Modal
                        title="删除预警事件"
                        visible={TipVisible}
                        onOk={this.handleTipOk}
                        okText={'确认'}
                        onCancel={this.handleTipCancel}
                        cancelText={'取消'}>
                        <p>{this.state.TipMSG}</p>
                    </Modal>
                </div>

                <Input
                    className={'ant-input'}
                    placeholder="输入风险事件ID以删除"
                    allowClear
                    onChange={this.onChangeDeleteSolutionInput.bind(this)}
                />
                <Button
                    type="danger"
                    onClick={this.handleDeleteSolution.bind(this)}>
                    删除
                </Button>
                <Button
                    type="primary"
                    onClick={this.handleAddSolution.bind(this)}>
                    添加解决方案
                </Button>

                <div style={{ float: 'right' }}>
                    <Select
                        className="sub-row2-select"
                        labelInValue
                        defaultValue={{ key: '请选择风险类型' }}
                        style={{ width: 150, height: 30, marginRight: '20px' }}
                        onChange={this.handleChangeType.bind(this)}
                        allowClear>
                        {this.state.riskTypes.map((item) => {
                            return (
                                <Option key={item.id} value={item.id}>
                                    {item.type}
                                </Option>
                            );
                        })}
                    </Select>
                    <Select
                        className="sub-row2-select"
                        labelInValue
                        defaultValue={{ key: '请选择参考水平' }}
                        style={{ width: 150, height: 30 }}
                        onChange={this.handleChangeLevel.bind(this)}
                        allowClear>
                        {this.state.referenceLevels.map((item) => {
                            return (
                                <Option key={item.id} value={item.id}>
                                    {item.level}
                                </Option>
                            );
                        })}
                    </Select>
                    <Button
                        type="primary"
                        icon="search"
                        shape="circle"
                        onClick={this.handleClickForSearch.bind(this)}
                    />
                </div>
                <br />
                <Row className="sub-row2">
                    <Table
                        className="emergency-table"
                        columns={this.state.columns}
                        dataSource={this.state.indexList}
                        pagination={false}
                    />
                    ,
                    <div style={{ float: 'right' }}>
                        <PageComponent
                            total={this.state.totalNum}
                            current={this.state.current}
                            totalPage={this.state.totalPage}
                            goValue={this.state.goValue}
                            pageClick={this.pageClick.bind(this)}
                            goPrev={this.goPrevClick.bind(this)}
                            goNext={this.goNext.bind(this)}
                            switchChange={this.goSwitchChange.bind(this)}
                        />
                    </div>
                </Row>
                <Modal
                    title="添加解决方案"
                    visible={visible}
                    onOk={this.handleOk}
                    okText={'确认'}
                    confirmLoading={confirmLoading}
                    onCancel={this.handleCancel}
                    cancelText={'取消'}>
                    <WrappedAddSolutionForm ref="getFormVlaue" />
                </Modal>
            </div>
        );
    }
}

export default ManageRisk;
